import java.util.*;
import java.io.*;

public class Example {
    public static void main(String args[]) {
        File folder = new File("主角们的简介");
        String replaced, target;
        Scanner in = new Scanner(System.in);
        System.out.println("请输入要替换的单词。");
        System.out.print(">");
        replaced = in.next();
        System.out.println("想要把它替换成什么单词？");
        System.out.print(">");
        target = in.next();
        processFolder(folder, replaced, target);
    }

    private static void processFolder(File folder, String replaced, String target) {
        File[] files = folder.listFiles();
        for (File file : files) {
            if (file.isDirectory()) processFolder(file, replaced, target);
            else {
                //为输出文件指定路径
                StringBuilder outputFilePath = new StringBuilder(file.getPath());
                outputFilePath.insert(outputFilePath.length() - 4, " - Modified");
                File outputFile = new File(outputFilePath.toString());
                //处理文件
                try (Scanner in = new Scanner(file);
                     PrintWriter out = new PrintWriter(outputFile);) {
                    while (in.hasNext()) {
                        StringBuilder line = new StringBuilder(in.nextLine());
                        int current = 0;
                        while (current <= line.length() - 1) {
                            current = line.indexOf(replaced, current);
                            //一行中的所有单词已完成替换
                            if (current < 0) break;
                            line.replace(current, current + replaced.length(), target);
                            current += target.length();
                        }
                        out.println(line);
                    }
                }
                catch (IOException ex) {
                    ex.printStackTrace();
                }
            }
        }
    }
}
